<?php
namespace app\common\behavior;

use think\Db;
use think\helper\Time;

class WriteLog
{
    public function run(&$params)
    {
        if(config('base.write_log')==true){
            $request = request();
            $module = $request->module();
            $controller = $request->controller();
            $action = $request->action();
            $no_write_moudle = config('base.no_write_moudle');
            $no_write_controller = config('base.no_write_controller');
            $no_write_action = config('base.no_write_action');
            if($request->isAjax()){
                if(!in_array($module,$no_write_moudle)){
                    if(!in_array($controller,$no_write_controller)){
                        if(!in_array($action,$no_write_action)){
                            $this->writeLog($module,$controller,$action);
                        }
                    }
                }
            }
        }else{
            cache('logs_data',null); //清除缓存
        }
    }

    /**
     * 写入日志
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    private function writeLog($module,$controller,$action){
        $request = request();
        $data['module'] = $module;
        $data['controller'] = $controller;
        $data['action'] = $action;
        $data['url'] = $request->url();
        $data['ip'] = $request->ip();
        $data['data'] = json_encode($request->param());
        $data['create_time']=time();
        $utype = $data['module'];
        $res = is_login($utype);
        if($res===false){
            $uid = 0;
        }else{
            $uid = $res['uid'];
        }
        $username='';
        if($uid>0){
            $username = Db::table('user')->where('uid',$uid)->value('username');
        }
        $data['utype'] = $utype;
        $data['uid'] = $uid;
        $data['username'] = $username;
        $logs = cache('logs_data');
        $logs[]=$data;
        if(count($logs)>=120){
            cache('logs_data',null);
            //只保留3天内数据
            $time30Day = Time::daysAgo('3');
            Db::table('action_log')->where('create_time', '<', $time30Day)->delete();
            Db::table('action_log')->insertAll($logs);
        }else{
            cache('logs_data',$logs);
        }
        return $data;
    }
}